package top.scsoul.pas.service.impl;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import top.scsoul.pas.entity.Achievement;
import top.scsoul.pas.entity.ExamInfo;
import top.scsoul.pas.entity.User;
import top.scsoul.pas.repository.AchievementRepository;
import top.scsoul.pas.repository.ExamInfoRepository;
import top.scsoul.pas.service.ExamInfoService;

import javax.transaction.Transactional;
import java.util.List;

@Transactional(rollbackOn = Exception.class)
@Slf4j
@Service
public class ExamInfoServiceImpl implements ExamInfoService {
    @Autowired
    ExamInfoRepository examInfoRepository;
    @Autowired
    AchievementRepository achievementRepository;

    @Override
    public void addExamInfo(ExamInfo examInfo) {
        examInfoRepository.save(examInfo);
    }

    @Override
    public List<ExamInfo> findByCreator(User user, int currentPage, int pageSize) {
        List<ExamInfo> examInfoList = examInfoRepository.findAllByCreator(user.getId());
        return examInfoList;
    }

    @Override
    public Page<ExamInfo> findAll(int currentPage, int pageSize) {
        Sort sort = Sort.by(Sort.Direction.DESC, "created");
        PageRequest pageRequest = PageRequest.of(currentPage - 1, pageSize, sort);
        return examInfoRepository.findAll(pageRequest);
    }

    @Override
    public void deleteExamInfo(Long id) {
        //先删除成绩表种的外键关联
        achievementRepository.delByExamInfo(id);
        examInfoRepository.deleteById(id);
    }

    @Override
    public ExamInfo findById(Long id) {
        return examInfoRepository.getById(id);
    }


}
